package com.frejoys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frejoys.common.dto.app.AddUserAddressDto;
import com.frejoys.common.dto.app.UpdateAddressDto;
import com.frejoys.common.enums.EAddressStatus;
import com.frejoys.common.error.HttpStatus;
import com.frejoys.common.exception.GeneralException;
import com.frejoys.common.vo.app.UserAddressVo;
import com.frejoys.common.vo.common.AdcodeVo;
import com.frejoys.dao.entity.UserAddress;
import com.frejoys.dao.mapper.UserAddressMapper;
import com.frejoys.service.AreaService;
import com.frejoys.service.UserAddressService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements UserAddressService {

    private final AreaService areaService;

    //添加收获地址
    @Override
    public Integer addUserAddress(Long userId, AddUserAddressDto addUserAddressDto) {
        LambdaQueryWrapper<UserAddress> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserAddress::getUserId, userId);
        wrapper.ne(UserAddress::getStatus, EAddressStatus.del.getValue());
        Long count = baseMapper.selectCount(wrapper);

        if (count >= 10) {
            throw new GeneralException(HttpStatus.addressError);
        }

        AdcodeVo adcodeVo = areaService.getProvinceCityDistrict(addUserAddressDto.getDistrict());

        UserAddress userAddress = new UserAddress();
        userAddress.setUserId(userId);
        userAddress.setName(addUserAddressDto.getName());
        userAddress.setPhone(addUserAddressDto.getPhone());
        userAddress.setStatus(EAddressStatus.off.getValue());
        userAddress.setAddress(addUserAddressDto.getAddress());
        userAddress.setDistrict(addUserAddressDto.getDistrict());
         userAddress.setStreet(addUserAddressDto.getStreet());
        userAddress.setCity(adcodeVo != null ? adcodeVo.getCity() : null);
        userAddress.setProvince(adcodeVo != null ? adcodeVo.getProvince() : null);

        return baseMapper.insert(userAddress);
    }

    //查看我的收货地址
    @Override
    public List<UserAddressVo> userAddressList(Long userId) {
        LambdaQueryWrapper<UserAddress> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserAddress::getUserId, userId);
        wrapper.ne(UserAddress::getStatus,EAddressStatus.del.getValue());
        List<UserAddress> userAddresses = baseMapper.selectList(wrapper);
        List<UserAddressVo> list = new ArrayList<>();

        if (!userAddresses.isEmpty()) {
            Map<String, String> areaMap = areaService.getNameMap();

                for (int i = 0; i < userAddresses.size(); i++){

                    UserAddress userAddress = userAddresses.get(i);
                    UserAddressVo vo = new UserAddressVo();

                    vo.setAddress(userAddress.getAddress());
                    vo.setDistrictName(areaMap.get(userAddress.getDistrict()));
                    vo.setProvinceName(areaMap.get(userAddress.getProvince()));
                    vo.setCityName(areaMap.get(userAddress.getCity()));
                    vo.setDistrict(userAddress.getDistrict());
                    vo.setProvince(userAddress.getProvince());
                    vo.setCity(userAddress.getCity());
                    vo.setStreet(userAddress.getStreet());
                    vo.setId(userAddress.getId());
                    vo.setName(userAddress.getName());
                    vo.setPhone(userAddress.getPhone());
                    vo.setStatus(userAddress.getStatus());

                    if (userAddress.getStatus() == EAddressStatus.off.getValue()){
                        list.add(vo);

                        //排序 默认收货地址排到最前
                    }else if (userAddress.getStatus() == EAddressStatus.on.getValue()){
                        list.add(vo);
                        Collections.rotate(list,-i);
                    }

                }




        }
        return list;
    }


    /** 修改收获地址信息
     *
     * @param dto
     * @return
     */
    @Override
    public Integer updateAddress(UpdateAddressDto dto) {

//        AdcodeVo adcodeVo = areaService.getProvinceCityDistrict(dto.getDistrict());

        LambdaUpdateWrapper<UserAddress> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(UserAddress::getId,dto.getId());

        if (StrUtil.isNotEmpty(dto.getName())){
            wrapper.set(UserAddress::getName,dto.getName());
        }
        if (StrUtil.isNotEmpty(dto.getPhone())){
            wrapper.set(UserAddress::getPhone,dto.getPhone());
        }
//        if (StrUtil.isNotEmpty(dto.getProvince())){
//            wrapper.set(UserAddress::getProvince,dto.getProvince());
//        }
//        if (StrUtil.isNotEmpty(dto.getCity())){
//            wrapper.set(UserAddress::getCity,dto.getCity());
//        }
        // 根据区编码,查询填充省市编码
        if (StrUtil.isNotEmpty(dto.getDistrict())){
            LambdaQueryWrapper<UserAddress> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(UserAddress::getDistrict);
            queryWrapper.eq(UserAddress::getId,dto.getId());
            UserAddress userAddress = getOnly(queryWrapper);
            if (userAddress!=null && !dto.getDistrict().equals(userAddress.getDistrict())) {
                wrapper.set(UserAddress::getDistrict,dto.getDistrict());
                AdcodeVo adcodeVo = areaService.getProvinceCityDistrict(dto.getDistrict());
                if (adcodeVo != null) {
                    wrapper.set(UserAddress::getProvince,adcodeVo.getProvince());
                    wrapper.set(UserAddress::getCity,adcodeVo.getCity());
                }
            }

        }
        if (StrUtil.isNotEmpty(dto.getStreet())){
            wrapper.set(UserAddress::getStreet,dto.getStreet());
        }
        if (StrUtil.isNotEmpty(dto.getAddress())){
            wrapper.set(UserAddress::getAddress,dto.getAddress());
        }
        return baseMapper.update(wrapper);
    }


    /**设置默认收获地址
     *
     * @param userId 用户id
     * @param id 收货地址id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer setOnAddress(Long userId, Integer id) {
        //先查询有没有默认收获地址
        LambdaQueryWrapper<UserAddress> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(UserAddress::getId);
        wrapper.eq(UserAddress::getUserId,userId);
        wrapper.eq(UserAddress::getStatus,EAddressStatus.on.getValue());
        UserAddress userAddress = getOnly(wrapper);

        //之前有默认地址 先设置为正常地址
        if (userAddress != null){
            LambdaUpdateWrapper<UserAddress> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(UserAddress::getStatus,EAddressStatus.off.getValue());
            updateWrapper.eq(UserAddress::getId,userAddress.getId());

            baseMapper.update(updateWrapper);
        }

        LambdaUpdateWrapper<UserAddress> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(UserAddress::getStatus,EAddressStatus.on.getValue());
        updateWrapper.eq(UserAddress::getId,id);

        return baseMapper.update(updateWrapper);
    }


    //删除收获地址
    @Override
    public Integer deleteAddress(Integer id) {
        LambdaUpdateWrapper<UserAddress> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(UserAddress::getStatus,EAddressStatus.del.getValue());
        wrapper.eq(UserAddress::getId,id);

        return baseMapper.update(wrapper);
    }

}
